<!-- —————————————————————————————————————— 采购入库 —————————————————————————————————————— -->

<template>
  <div class="Purchase clear">
    <!-- —————————————— 操作框 —————————————— -->
    <div class="header">
      <!-- <el-button type="primary" >添加药品</el-button> -->
      <el-button type="primary" class="add" @click="add">添加药品</el-button>
      <el-button type="primary" class="check" @click="commit(0)"
        >提交审核</el-button
      >
      <el-button type="primary" class="InStorage"  @click="commit(1)">直接入库</el-button>
    </div>

    <!-- —————————————— 搜索框 ——————————————  -->
    <div class="nav">
      <p>
        单据号：{{
          billId
        }}
        &nbsp;&nbsp;&nbsp;制单人：<span>{{ loginUser }}</span>
      </p>
      <div class="navRight">
        <el-form ref="form" :model="sizeForm" label-width="auto">
          <!-- 供应商 -->
          <el-form-item label="供应商">
            <el-select v-model="sizeForm.region" placeholder="选择供应商">
              <el-option label="选择供应商" value="" />
              <el-option label="供应商A" value="beijing" />
              <el-option label="供应商B" value="shanghai" />
            </el-select>
          </el-form-item>

          <!-- 制单日期 -->
          <el-form-item label="制单日期">
            <el-col :span="24">
              <el-date-picker
                v-model="sizeForm.date1"
                type="date"
                label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
              />
            </el-col>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- —————————————— 计算金额 —————————————— -->
    <div class="computed clear">
      <p>
        批发总金额：<span>{{ getPresption }}</span>
      </p>
      <p>
        处方总金额：<span>{{ getSholesale }}</span>
      </p>
      <div>
        <el-button type="danger" class="clearNum" @click="clearNum"
          >清空数值</el-button
        >
      </div>
    </div>

    <!-- —————————————— 表格 —————————————— -->
    <el-table
      ref="multipleTableRef"
      @selection-change="handleSelectionChange4"
      :data="getAllData"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="id" label="序号" />
      <el-table-column prop="drugName" label="药品名称" />
      <el-table-column prop="drugUnit" label="规格" />
      <el-table-column prop="drugFactory" label="生产厂家" />
      <el-table-column prop="drugNumber" label="数量">
        <template #default="scope">
          <el-input-number
            @focus="setFocus(scope.row)"
            :step="0.01"
            :controls="false"
            size="small"
            placeholder="0"
            @change="changeNumber"
            @selection-change="handleSelectionChange2"
          />
        </template>
      </el-table-column>
      <el-table-column prop="drugSpecification" label="单位" />

      <el-table-column prop="trade" label="批发价">
        <template #default="scope">
          <el-input-number
            @focus="setFocus(scope.row)"
            :step="0.01"
            :controls="false"
            size="small"
            placeholder="0"
            @change="changePrice1"
          />
        </template>
      </el-table-column>
      <el-table-column prop="prescription" label="处方价">
        <template #default="scope">
          <el-input-number
            @focus="setFocus(scope.row)"
            :step="0.01"
            :controls="false"
            size="small"
            placeholder="0"
            @change="changePrice2"
          />
        </template>
      </el-table-column>
      <el-table-column prop="trades" label="批发额"> </el-table-column>
      <el-table-column prop="pres" label="处方额"> </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click.prevent="delClick(scope.$index)"
            >删除</el-button
          >
          <!-- <el-button link type="primary" size="small" @click="update(scope.row)"
            >修改</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <!-- —————————————— 分页 ——————————————  -->
    <div class="demo-pagination-block">
      <el-pagination
        small
        background
        layout="prev, pager, next"
        :total="getAllData.length"
        class="mt-4"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!-- —————————————— 添加药品 —————————————— -->
  <div id="addMedicine">
    <el-dialog v-model="dialogFormVisible" title="添加药品">
      <!-- 药品名称 -->
      <div class="medicines">
        <span>药品编号</span
        ><el-input
          class="medicineName"
          v-model="str"
          placeholder="输入药品编号"
          @blur="handleBlur"
          clearable
        />
      </div>

      <!-- 药品分类 -->
      <div class="medicines">
        <span>药品分类</span>
        <el-select class="medicineClassify" placeholder="全部">
          <el-option value="both">全部</el-option>
          <el-option value="middle">中草药</el-option>
        </el-select>
      </div>

      <!-- 添加表格 -->
      <!-- :data="getAddData" -->
      <el-table
        :data="getAddData"
        style="width: 100%"
        ref="multipleTableRef"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column fixed prop="drugId" label="药品编号" />
        <el-table-column prop="drugName" label="药品名称" />
        <el-table-column prop="drugUnit" label="规格" />
        
      <el-table-column prop="drugSort" label="" disabled/>
        <el-table-column prop="drugFactory" label="生产厂家" />
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button class="addBtn" @click="AddCancle">取消</el-button>
          <el-button class="addBtn" type="primary" @click="addSure">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>

  <!-- —————————————— 修改弹框 —————————————— -->
  <div id="updateMedicine">
    <!-- totalPres 获取修改后的批发额额 和处方额 -->
    <el-dialog v-model="updateVisible" title="修改药品信息" :name="totalPres">
      <!-- 药品名称 -->
      <div class="medicines2">
        <span>药品名称</span
        ><el-input
          class="medicineNames"
          v-model="medicineName"
          placeholder="输入药品名称"
          clearable
        />
      </div>

      <!-- 规格 -->
      <div class="medicines2">
        <span>规格</span
        ><el-input
          class="medicineSpec"
          v-model="medicineSpec"
          placeholder="规格"
          clearable
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button class="addBtn" @click="UpdateCancle">取消</el-button>
          <el-button class="addBtn" type="primary" @click="UpdateSure">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script lang="ts" setup>
/* ———————————————————————— 引入模块 ————————————————————————  */
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "@/utils/http";
import { mapGetters, mapMutations, useStore } from "vuex";
import router from "@/router";

const billId = ref("")
onMounted(()=>{
  let date = new Date();
  let datestr = date.toLocaleDateString().replaceAll("/","")
  billId.value = ""+datestr+date.getTime().toString().substring(6);
})

const store = useStore();

//印设数量的变化
const changeNumber = mapMutations(["changeNumber"]).changeNumber.bind({
  $store: store,
});

//印设批发价的变化
const changePrice2 = mapMutations(["changePrice2"]).changePrice2.bind({
  $store: store,
});

//印设处方价的变化
const changePrice1 = mapMutations(["changePrice1"]).changePrice1.bind({
  $store: store,
});

//印设获焦事件
const setFocus = mapMutations(["setFocus"]).setFocus.bind({
  $store: store,
});
/* ———————————————————————— 表格数据 ———————————————————————— */
//发请求获取表格数据
const setAllData = mapMutations(["setAllData"]).setAllData.bind({
  $store: store,
});

//把保存的数据存下来
const saveDrugData = mapMutations(["saveDrugData"]).saveDrugData.bind({
  $store: store,
});

//印设获取所有的数据
const getAllData = computed(
  mapGetters(["getAllData"]).getAllData.bind({
    $store: store,
  })
);

//印设计算表格里面的 批发价和处方价
const totalPres = computed(
  mapGetters(["totalPres"]).totalPres.bind({
    $store: store,
  })
);

setAllData();

/* ———————————————————————— 搜索 ———————————————————————— */
//搜索框
const sizeForm = reactive({
  region: "",
  date1: "",
});

/* ———————————————————————— 分页 ———————————————————————— */
//点击改变当前页码
const handleCurrentChange = (val: number) => {
  console.log(`当前页: ${val}`);
};

/* ——————————————————————————————————  添加药品 —————————————————————————————————— */
//添加框是否显示
const dialogFormVisible = ref(false);
//请求的添加数据
const setAddData = mapMutations(["setAddData"]).setAddData.bind({
  $store: store,
});

//印设
const getAddData = computed(
  mapGetters(["getAddData"]).getAddData.bind({
    $store: store,
  })
);

/* —————点击添加按钮——————— */
const add = () => {
  console.log("点击添加药品");
  dialogFormVisible.value = !dialogFormVisible.value;
  console.log(axios);
  setAddData();
};

//添加框里面的值
let medicineName = ref("");
let form = ref({
  region: "",
});

//取消添加
const AddCancle = () => {
  dialogFormVisible.value = false;
  ElMessage({
    showClose: true,
    message: "已取消添加",
  });
};

//确定添加
const addSure = () => {
  console.log("确定添加");
  dialogFormVisible.value = false;
  saveDrugData(multipleSelection);
  //把数据添加到原网页的表格中
};

/* ————— 添加值变化 ——————— */
let num = ref();
let trade = ref();
let prescription = ref();

let value1;
let handleBlur2 = () => {
  console.log("失去焦点");
  console.log(num.value, trade.value, prescription.value);
  value1 = num.value * trade.value;
};
// console.log('value1',value1);

let AllData = store.state.purchase.allData;

/* ———————————————————————— 添加框里 失焦发起搜索请求  ———————————————————————— */
let str = ref("");
const setSearchData = mapMutations(["setSearchData"]).setSearchData.bind({
  $store: store,
});

//印设
const getSearchData = computed(
  mapGetters(["getSearchData"]).getSearchData.bind({
    $store: store,
  })
);

/* 失焦事件 */
const handleBlur = () => {
  console.log("失焦事件");
  setSearchData({ str: str.value });
};

/* ———————————————————————— 多选行 ———————————————————————— */
const multipleSelection = ref<User[]>([]);

//每一行的数据类型
interface User {
  date: string;
  name: string;
  address: string;
}

//多选的内容
const handleSelectionChange = (val:any) => {
  multipleSelection.value = val;
  console.log("test",val);
  console.log("test",multipleSelection.value);
};

//表格多选行的数据
const handleSelectionChange2 = (val: User[]) => {
  multipleSelection.value = val;

  console.log(val);
};
/* ————————————————————————— 单条数据删除 ————————————————————————— */
const delClick = (id: number) => {
  console.log("点击了删除", id);
  //点击删除，弹出确认框
  ElMessageBox.confirm("确认删除本条数据吗?", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      //点击确认删除
      getAllData.value.splice(id, 1);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      //重新获取数据
    })
    .catch(() => {
      //点击取消删除
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

/* ————————————————————————— 修改 ————————————————————————— */
//修改弹框
//添加框是否显示
const updateVisible = ref(false);
let updateValue;
let medicineNames = ref("");
let medicineSpec = ref("");
const update = (row: number) => {
  updateValue = row;
  console.log("点击了修改按钮", updateValue);
  //点击修改，修改框显示
  updateVisible.value = !updateVisible.value;
};

//取消修改
let UpdateCancle = () => {
  updateVisible.value = false;
  ElMessage({
    showClose: true,
    message: "已取消修改",
  });
};

//确认修改
let UpdateSure = () => {
  updateVisible.value = false;
  ElMessage({
    showClose: true,
    message: "修改成功",
    type: "success",
  });

  console.log(medicineNames, medicineSpec);
};

/* ————————————————————————— 计算批发总金额函数 ————————————————————————— */

//印设
const getSholesale = computed(
  mapGetters(["getSholesale"]).getSholesale.bind({
    $store: store,
  })
);

/* ————————————————————————— 计算处方总金额函数 ————————————————————————— */
//印设
const getPresption = computed(
  mapGetters(["getPresption"]).getPresption.bind({
    $store: store,
  })
);

/* ————————————————————————— 清空数值 ————————————————————————— */
let clearNum = () => {
  console.log("点击了清空数值");
  setClear();
};

//印设
const setClear = mapMutations(["setClear"]).setClear.bind({
  $store: store,
});

/* ————————————————————————— 制单人 ————————————————————————— */
let loginUser = ref(""); //登录者名字
//获取到登录者
let user = store.state.router.userData.userInfo.empUserName;
loginUser = user;
console.log("登录者", loginUser);

/* ————————————————————————— 单据号 ————————————————————————— */



/* _______________________测试 */
/* ————————————————————————— 提交审核 ———————————————————————— */

//假数据
const tableData = [
  {
    id: 1,
    drugId: 1001,
    drugName: "阿松",
    drugUnit: "件",
    drugFactory: "阿松",
    drugSpecification: "kg",
    drugNumber: 20,
    trade: 12,
    prescription: 12,
    trades: 12,
    pres: 12,
  },
];

//获取主页表格的数据集
const handleSelectionChange4 = (val: User[]) => {
  multipleSelection.value = val;
  console.log("val", val);
};

//提交审核
const commit = (status:any) => {empUserName
  let date2 = new Date()
  console.log("提交审核",multipleSelection.value);
  //获取到添数据
  let empUserName = null;
  let checkTime = null;
  console.log(sizeForm.date1);
  if(store.state.router.userData.userInfo.empUserName==undefined){
    ElMessage("请先登录");
    router.push({
    path: "/login"
  });
    return
  }else{
    empUserName = store.state.router.userData.userInfo.empUserName
    const year=String(date2.getFullYear())
 const mon=String(date2.getMonth()+1)
 const day=String(date2.getDate())
    checkTime = year+"-"+mon+"-"+day+" "+date2.toLocaleTimeString()
  }
  if(sizeForm.region==""){
    ElMessage("请选择供应商");
    return
  }
  else if(sizeForm.date1==""){
    ElMessage("请选择日期");
    return 
  }

  let date = new Date(sizeForm.date1)
 
  let datestr = date.toLocaleDateString().replaceAll("/","")
  const year=String(date.getFullYear())
 const mon=String(date.getMonth()+1)
 const day=String(date.getDate())
 datestr=year+"-"+mon+"-"+day
  let drugOrderList2 = JSON.parse(JSON.stringify(getAllData.value))
  console.log(drugOrderList2);
  let drugOrderList = <any>[]
  drugOrderList2.forEach((item:any) => {
    drugOrderList.push({
      ...item,
      billId:billId.value,
      status:status,
    })
  });
  let data = {
  "drugBill": {
    "allPre": getPresption.value,
    "allTrade": getSholesale.value,
    "checkTime": checkTime,
    "checker": empUserName,
    "id": billId.value,
    "purchTime": datestr+" 00:00:00" ,
    "purchaser": "aa",
    "status": status,
    "supName": sizeForm.region
  },
  "drugOrderList": drugOrderList
  
    }
    console.log(data);
    
  //发请求
  axios({
    url:'/medicine/purchase/SubmitCheck',
    method:'post',
    data:data
  }).then( (res)=> {
    console.log(res);
    
  }).catch( (err)=> {
    console.log(err);
    
  })
};
</script>
  
  <style scoped>
* {
  padding: 0;
  margin: 0;
}

.clear::after {
  content: "";
  display: block;
  clear: both;
}
/* 外部背景 */
.Purchase {
  background: #f3f5f8;
}
/* 头部 */
.header {
  width: 100%;
  height: 70px;
  border: 1px solid rgb(234, 233, 233);
  box-shadow: 2px 1px rgb(234, 233, 233);
  background: white;
  margin: 35px 0;
  position: relative;
}

/* 添加按钮 */
.set {
  width: 130px;
  height: 42px;
  font-size: 16px;
  line-height: 70px;
  position: absolute;
  top: 14px;
  right: 470px;
}

/* 批量设置 */
.add {
  width: 130px;
  height: 42px;
  font-size: 16px;
  line-height: 70px;
  position: absolute;
  top: 14px;
  right: 320px;
}

/* 提交审核 */
.check {
  width: 130px;
  height: 42px;
  font-size: 16px;
  line-height: 70px;
  position: absolute;
  top: 14px;
  right: 170px;
}

/* 直接入库 */
.InStorage {
  width: 130px;
  height: 42px;
  font-size: 16px;
  line-height: 70px;
  position: absolute;
  top: 14px;
  right: 20px;
}

/* 搜索框 */
.nav {
  width: 100%;
  height: 70px;
  border: 1px solid rgb(234, 233, 233);
  box-shadow: 2px 1px rgb(234, 233, 233);
  margin-top: -25px;
  position: relative;
  background: white;
}

.nav > p {
  float: left;
  position: absolute;
  /*  ; */
  height: 24px;
  line-height: 24px;
  top: 23px;
}

.navRight {
  float: right;
  /*  ; */
  width: 580px;
  height: 40px;
  position: absolute;
  right: 20px;
  top: 15px;
  font-size: 20px;
}

.el-form-item {
  float: left;
  width: 280px;
  text-align: center;
  margin: 3px;
}

.asterisk-left {
  font-size: 20px;
}
/* .el-form-item asterisk-leftr{
       ;
  } */

/* 计算金额 */
.computed {
  width: 100%;
  height: 60px;
  background: #f3f5f8;
  position: relative;
}

.computed > p:nth-of-type(1) {
  float: left;
  position: absolute;
  right: 335px;
  height: 26px;
  top: 17px;
  font-size: 16px;
  /*  ; */
}

.computed > p:nth-of-type(2) {
  float: left;
  position: absolute;
  right: 165px;
  height: 26px;
  top: 17px;
  font-size: 16px;
  /*  ; */
}
.computed > div {
  float: left;
  position: absolute;
  right: 0px;
  top: 9px;
}

.computed > p:nth-of-type(1) > span,
.computed > p:nth-of-type(2) > span {
  color: red;
}
.clearNum {
  width: 130px;
  height: 42px;
}

/* 分页样式 */
.demo-pagination-block {
  width: 220px;
  margin: 20px auto;
}

/* 添加弹出框 */
.medicineName {
  width: 200px;
  margin: 0 10px;
}

.medicines {
  float: left;
  width: 300px;
  /*   ; */
}

.medicineClassify {
  width: 120px;
  margin: 0 10px;
}

.el-form {
  height: 300px;
}

.addBtn {
  width: 100px;
  height: 35px;
  line-height: 35px;
}

/* 修改弹框 */
.medicineNames {
  width: 400px;
  margin: 5px 10px;
}
.medicineSpec {
  width: 400px;
  margin: 5px 38px;
}

.oinput {
  width: 50px;
}
</style>